package com.zjitc.controller;

import com.zjitc.pojo.User;
import com.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录功能Controller
 *
 * @author Admin
 */
@Controller
public class LoginController {

    public static Integer role;

    public static String username;

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String getIndex() {
        return "login";
    }

    /**
     * 登录验证
     *
     * @param user    用户信息
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String getLogin(User user, HttpServletRequest request) {
        role = user.getRole();
        username = user.getUsername();
        if (userService.isLogin(user)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            return "redirect:/users/index";
        } else {
            return "redirect:/index";
        }
    }

    @RequestMapping("/registerEntry")
    public String registerEntry() {
        return "register";
    }

    @RequestMapping("/register")
    public String register(User user) {
        User find = userService.findByUserName(user.getUsername());
        if (find == null) {
            userService.insert(user);
            return "login";
        }
        return "register";
    }
}
